const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

//import router from './src/routes/main';
//import './src/routes/index';
//import './src/routes/users';
import { Context, Next } from 'koa';
import ds from './src/config/DataSource'
import 'reflect-metadata'
import { UserController } from './src/controller/UserController';
import { useExpressServer } from 'routing-controllers'

// 新增：初始化 DataSource
(async () => {
  await ds.initialize().then(() => {
    console.log('Data Source has been initialized!')
  })
  .catch((e: any) => {
    console.log('Error during Data Source initialization:', e)
  })
  console.log('Data source initialized')
})()

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/src/views', {
  extension: 'html'
}))

// routes
//app.use(router.routes());
//app.use(router.allowedMethods());

// console.log(router.stack.map(layer => ({
//   method: layer.methods,
//   path: layer.path
// })))

// logger
app.use(async (ctx: Context, next: Next) => {

  const { origin, referer } = ctx.headers;
  ctx.set({
    "Access-Control-Allow-Origin": "*", // 开启跨域，一般用于调试环境，正式环境设置指定 ip 或者指定域名
    // "Content-Type": "application/json",
    // "Access-Control-Allow-Credentials": "true",
    // "Access-Control-Allow-Methods": "OPTIONS, GET, PUT, POST, DELETE",
    "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization",
  });

  if (ctx.request.method === "OPTIONS") {
    ctx.response.status = 200;
  }

  const start: Date = new Date();
  await next()
  const ms: number = new Date().getTime() - start.getTime()
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// error-handling
app.on('error', (err: Error, ctx: Context) => {
  console.error('server error', err, ctx)
});

// 将当前实例注册到 routing-controllers
useExpressServer(app, {
    controllers: [UserController]
})

app.listen(3000);

module.exports = app
